﻿CREATE PROC [dbo].[usp_InsumoAgregarHijo](@mgrIdParte int, @idParte int, @cantidad int) 
AS 
BEGIN
   DECLARE @mOrgNode hierarchyid, @lc hierarchyid
   SELECT @mOrgNode = Jerarquia 
   FROM Insumo
   WHERE IdParte = @mgrIdParte
   SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
   BEGIN TRANSACTION

	If @mOrgNode is not null 
	begin
      SELECT @lc = max(Jerarquia) 
      FROM Insumo
      WHERE Jerarquia.GetAncestor(1) =@mOrgNode ;

      INSERT Insumo (idparte,jerarquia, cantidad)
      VALUES(@idParte, @mOrgNode.GetDescendant(@lc, NULL), @cantidad)
	END
	ELSE
	BEGIN
		INSERT Insumo (idparte,jerarquia, cantidad)
		VALUES(@idParte, hierarchyid::GetRoot().GetDescendant((select MAX(Jerarquia) from Insumo where Jerarquia.GetAncestor(1) = hierarchyid::GetRoot()),NULL), @cantidad)
	END
   COMMIT
END ;